﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.NewsAndBlogs.Controls
{
    public class BlogPostListControl : UserControl
    {
        protected HtmlAnchor firstPostProfileLink;
        protected HtmlImage firstPostProfileImage;
        protected HtmlAnchor firstPostTitle;
        protected HtmlAnchor firstPostAuthorLink;
        protected HtmlAnchor firstPostBlogLink;
        protected HtmlGenericControl firstPostDate;
        protected HtmlGenericControl firstPostSummary;
        protected HtmlAnchor firstPostReadMore;

        protected Repeater firstPostTagsRepeater;
        protected Repeater postsRepeater;

        protected HtmlGenericControl pager;
        protected HtmlGenericControl pagerPrevContainer;
        protected HtmlGenericControl pagerNextContainer;
        protected HtmlAnchor pagerPrevLink;
        protected HtmlAnchor pagerNextLink;

        protected HtmlGenericControl pagerBottom;
        protected HtmlGenericControl pagerBottomPrevContainer;
        protected HtmlGenericControl pagerBottomNextContainer;
        protected HtmlAnchor pagerBottomPrevLink;
        protected HtmlAnchor pagerBottomNextLink;

        private BlogRepository _blogRepository;

        private BlogRepository BlogRepository
        {
            get
            {
                if (_blogRepository == null)
                    _blogRepository = new BlogRepository(SPContext.Current.Web);

                return _blogRepository;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            firstPostTagsRepeater.ItemDataBound += TagsRepeaterItemDataBound;
            postsRepeater.ItemDataBound += PostsRepeaterItemDataBound;
        }
        protected void TagsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var keyword = (KeywordDto)e.Item.DataItem;

            var keywordAnchor = (HtmlContainerControl)e.Item.FindControl("keywordAnchor");
            keywordAnchor.InnerText = keyword.Title;
        }

        protected void PostsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var post = (BlogEntryDto)e.Item.DataItem;

            var titleLink = (HtmlAnchor)e.Item.FindControl("postTitleField");
            titleLink.HRef = "/uudised/blogid/Lehed/" + post.FileName;
            titleLink.InnerText = post.Title;

            //if (post.CommentsCount > 0)
            //    titleLink.InnerText += " (" + post.CommentsCount + ")";

            var commentsCountLink = (HtmlAnchor)e.Item.FindControl("commentsCountLink");
            if (post.Comments.Count > 0)
            {
                commentsCountLink.HRef = titleLink.HRef + "#comments";
                commentsCountLink.InnerHtml = "<span>(" + post.Comments.Count + ")</span>";
            }
            else
                commentsCountLink.Visible = false;

            var authorLink = (HtmlAnchor)e.Item.FindControl("authorField");
            authorLink.InnerText = post.Author;
            authorLink.HRef = "/profile.aspx?ID=" + post.ProfileId;

            var blogNameLink = (HtmlAnchor)e.Item.FindControl("blogNameField");
            blogNameLink.InnerText = post.BlogName;
            blogNameLink.HRef = "/uudised/blogid/Lehed/" + post.BlogUrl;

            var postDateField = (HtmlContainerControl)e.Item.FindControl("postDateField");
            postDateField.InnerText = post.Date.ToShortDateString();

            var summaryField = (Label)e.Item.FindControl("summaryField");
            summaryField.Text = post.Summary;

            var postLinkField = (HtmlAnchor)e.Item.FindControl("postLinkField");
            postLinkField.HRef = "/uudised/blogid/Lehed/" + post.FileName;

            var profileLink = (HtmlAnchor)e.Item.FindControl("profileLink");
            profileLink.HRef = authorLink.HRef;

            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var profile = profileRepository.GetUserProfileById(post.AuhtorId);

            var profileImage = (HtmlImage)e.Item.FindControl("profileImage");
            profileImage.Src = profile.UserImage32x32Url; // "/_layouts/enetahandlers/userimagehandler.ashx?size=32&id=" + post.ProfileId;

            var tagsRepeater = (Repeater)e.Item.FindControl("tagsRepeater");
            tagsRepeater.ItemDataBound += TagsRepeaterItemDataBound;
            tagsRepeater.DataSource = post.Keywords;
            tagsRepeater.DataBind();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
            {
                Response.Clear();
                Response.ContentType = "application/rss+xml";
                Response.Write(BlogRepository.GetBlogsRss());
                Response.End();
                return;
            }
            if (!string.IsNullOrEmpty(Request.QueryString["commentsrss"]))
            {
                Response.Clear();
                Response.ContentType = "application/rss+xml";
                Response.Write(BlogRepository.GetBlogCommentsRss());
                Response.End();
                return;
            }

            var master = Page.Master;
            if (master != null)
            {
                //var link = (HtmlGenericControl)master.FindControl("rssMetaUrl");
                var link = (HtmlLink)master.FindControl("rssMetaUrl");
                if (link != null)
                {
                    link.Attributes["title"] = "Eneta portaal: " + Resources.NewsAndBlogs.BlogsTitle;
                    link.Attributes["href"] = "http://rss.eneta.ee/eneta-blogid";
                }
            }

            try
            {
                Bind();
            }
            catch(Exception ex)
            {
                Logger.LogWarning("BlogPostListControl.OnLoad(): error binding data to control","");
                Logger.LogException(ex);
            }
        }

        protected void Bind()
        {
            var siteId = SPContext.Current.Site.ID;
            IList<BlogEntryDto> posts = new List<BlogEntryDto>();

            Trace.Write("BlogPostListControl.Bind(): asking posts");
            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                posts = GetPosts(siteId);
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
            Trace.Write("BlogPostListControl.Bind(): posts retrieved");

            if (posts.Count > 0)
            {
                BindFirstPost(posts[0]);
                posts.RemoveAt(0);
            }

            postsRepeater.DataSource = posts;
            postsRepeater.DataBind();
        }

        protected void BindFirstPost(BlogEntryDto firstPost)
        {
            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var profile = profileRepository.GetUserProfileById(firstPost.AuhtorId);

            firstPostProfileLink.HRef = "/profile.aspx?ID=" + firstPost.ProfileId;
            firstPostProfileImage.Src = profile.UserImage32x32Url; // "/_layouts/enetahandlers/userimagehandler.ashx?size=32&id=" + firstPost.ProfileId;
            firstPostTitle.InnerText = firstPost.Title;
            firstPostTitle.HRef = "/uudised/blogid/Lehed/" + firstPost.FileName;
            firstPostAuthorLink.InnerText = firstPost.Author;
            firstPostAuthorLink.HRef = "/profile.aspx?ID=" + firstPost.ProfileId;
            firstPostBlogLink.InnerText = firstPost.BlogName;
            firstPostBlogLink.HRef = "/uudised/blogid/Lehed/" + firstPost.BlogUrl;
            firstPostDate.InnerText = firstPost.Date.ToString(@"dd\.MM\.yyyy");
            firstPostSummary.InnerText = firstPost.Summary;
            firstPostReadMore.HRef = firstPostTitle.HRef;

            firstPostTagsRepeater.DataSource = firstPost.Keywords;
            firstPostTagsRepeater.DataBind();
        }


        protected IList<BlogEntryDto> GetPosts(Guid siteId)
        {
            var rep = new BlogRepository(SPContext.Current.Web);

            int page;
            var pageSize = 10;
            int.TryParse(Request.QueryString["page"], out page);
            if (page < 1)
                page = 1;

            var result = rep.GetApprovedEntries(page, pageSize);

            if (Math.Max(1, page - 1) == 1)
                pagerPrevLink.HRef = "/uudised/blogid/Lehed/default.aspx";
            else
                pagerPrevLink.HRef = "/uudised/blogid/Lehed/default.aspx?page=" + Math.Max(1, page - 1);
            pagerBottomPrevLink.HRef = pagerPrevLink.HRef;

            if (Math.Min(result.PageCount, page + 1) == 1)
                pagerNextLink.HRef = "/uudised/blogid/Lehed/default.aspx";
            else
                pagerNextLink.HRef = "/uudised/blogid/Lehed/default.aspx?page=" + Math.Min(result.PageCount, page + 1);
            pagerBottomNextLink.HRef = pagerNextLink.HRef;

            if (page <= 1)
                pagerPrevContainer.Visible = false;
            if (page >= result.PageCount)
                pagerNextContainer.Visible = false;

            pagerBottomPrevContainer.Visible = pagerPrevContainer.Visible;
            pagerBottomNextContainer.Visible = pagerNextContainer.Visible;

            return result.Results;
        }
    }
}
